﻿#define  _CRT_SECURE_NO_WARNINGS 1
#include <iostream>
#include <vector>
using namespace std;

//将x减到0的最小操作数
//滑动窗口

class Solution
{
public:
	int minOperations(vector<int>& nums, int x)
	{
		//简洁版
		//int sum = 0;
		//for (int a : nums) sum += a;
		//int target = sum - x;
		//// 细节问题 
		//if (target < 0) return -1;
		//int ret = -1;
		//for (int left = 0, right = 0, tmp = 0; right < nums.size(); right++)
		//{
		//	tmp += nums[right]; // 进窗⼝ 
		//	while (tmp > target) // 判断 
		//		tmp -= nums[left++]; // 出窗⼝ 
		//	if (tmp == target) // 更新结果 
		//		ret = max(ret, right - left + 1);
		//}
		//if (ret == -1) return ret;
		//else return nums.size() - ret;

		//屎山版
        int target = 0;
        for (auto e : nums) {
            target += e;
        }
        target -= x;
        if (target < 0) {
            return -1;
        }
        else if (target == 0) {
            return nums.size();
        }
        int r = 0;
        int l = 0;
        int len = 0;
        int sum = 0;
        for (int r = 0; r < nums.size(); r++) {
            sum += nums[r];
            while (sum > target) {
                sum -= nums[l++];
            }
            if (sum == target) {
                len = max(len, r - l + 1);
            }
        }
        if (len == 0) {
            return -1;
        }
        return nums.size() - len;

	}
};
